package com.ruoyi.personnel.controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.personnel.domain.Transfer;
import com.ruoyi.personnel.domain.WxUser;
import com.ruoyi.personnel.service.IPersonnelService;
import com.ruoyi.personnel.service.TransferService;
import com.ruoyi.personnel.service.WechatService;
import com.ruoyi.personnel.service.impl.WechatServiceImpl;
import com.ruoyi.personnel.wechat.utils.AESDecryption;
import com.ruoyi.personnel.wechat.utils.WechatUtil;
import com.ruoyi.system.service.ISysUserService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@RestController
public class WechatController extends BaseController {
@Autowired
    public WechatService wechatService;
@Autowired
public ISysUserService iSysUserService;
@Autowired
public WechatServiceImpl wechatServiceImpl;
    @Autowired
    public TransferService transferService;
    @Autowired
    private IPersonnelService personnelService;
    @Anonymous
//    匿名访问
    @PostMapping("/wechat/getSessionKey")

        public R wechatGetSessionKey(@RequestParam(value = "code",required = false) String code, @RequestParam(value = "signature",required = false) String signature, @RequestParam(value = "rawData",required = false) String rawData)
    {
        JSONObject jsonObject= WechatUtil.getSessionKeyOrOpenId(code);
        System.out.println(jsonObject.get("session_key"));
//        String sessionKey=jsonObject.get("session_key").toString();
        String openId=jsonObject.get("openid").toString();
        Object o=wechatServiceImpl.checkLogin(openId);
        System.out.println("json内容");
        System.out.println(jsonObject);
//
        System.out.println("查询数量");
        System.out.println(o);
        System.out.println("微信openid");
        System.out.println(jsonObject.get("openid"));
        System.out.println("转换");
        System.out.println(R.ok(jsonObject));
        jsonObject.put("code",o);
        if ((boolean)o){
            jsonObject.put("info","登录成功");
            return R.ok(jsonObject.get("openid"));
        }
        else {
            jsonObject.put("info","未登录请登录");
            return R.fail(jsonObject);
        }


    }
    @Anonymous
    @PostMapping("/wechat/decription")
    public R wechatUserdecription(@RequestParam(value = "session_key",required = false) String session_key, @RequestParam(value = "encryptedData",required = false) String encryptedData,@RequestParam(value = "iv",required = false) String iv) {
        if (encryptedData == null || iv == null) {
            return R.fail(405, "请获取手机信息");
        }
        String phoneNumber = JSONObject.parseObject(AESDecryption.decrypt(encryptedData, session_key, iv)).get("phoneNumber").toString();
        WxUser wxUser = new WxUser();
        wxUser.setWxPhoneNum(phoneNumber);
        Transfer transfer=new Transfer();
        JSONObject res=new JSONObject();
        if (wechatService.getWxUserList(wxUser) != null) {
            if (transferService.selectTransferByPhone(phoneNumber) != null) {
                if (transferService.selectTransferByPhone(phoneNumber).getUserIdCard() == null){
                    res.put("code",406);
                    res.put("msg","没有实名信息");
                    res.put("userId",transferService.selectTransferByPhone(phoneNumber).getUserId());
                    res.put("userPhone",transferService.selectTransferByPhone(phoneNumber).getUserPhone());
                    return R.fail(res);
                }
                res.put("userPhone",transferService.selectTransferByPhone(phoneNumber).getUserPhone());
                res.put("code",200);
                res.put("msg","成功登录");
//                res.put("data",)
                return R.ok(res);
            } else
                res.put("code",406);
                res.put("msg","登录失败");
                return R.fail(res);

        }
        else
        {return R.fail(405, "请绑定手机号,或者重新注册");}
//        System.out.println(JSONObject.parseObject(AESDecryption.decrypt(encryptedData,session_key,iv)).get("phoneNumber"));
//        return R.ok(AESDecryption.decrypt(encryptedData,session_key,iv));
    }
/*
注册类
**/
    @Anonymous
    @PostMapping("/wechat/wechatRegistUser")
    public R wechatRegistUser(@RequestParam(value = "openid",required = false) String openid,
                              @RequestParam(value = "nickname",required = false) String nickname,
                              @RequestParam(value = "avatarUrl",required = false) String avatarUrl,
                              @RequestParam(value= "gender",required = false) String gender,
                              @RequestParam(value = "phoneNumber",required = false) String phoneNumber,
                              @RequestParam(value = "session_key",required = false) String session_key,
                              @RequestParam(value = "encryptedData",required = false) String encryptedData,
                              @RequestParam(value = "iv",required = false) String iv,
                              @RequestParam(value = "code",required = false) String code,
                              @RequestParam(value = "signature",required = false) String signature,
                              @RequestParam(value = "rawData",required = false) String rawData
                              ) {
        System.out.println(rawData);
        JSONObject raw=JSON.parseObject(rawData);
        if (raw.get("nickName")!=null){
            nickname=raw.get("nickName").toString();
        }
        if (raw.get("gender")!=null){
            gender=raw.get("gender").toString();
        }
        if (raw.get("avatarUrl")!=null){
            avatarUrl=raw.get("avatarUrl").toString();
        }
//        解密
        if (phoneNumber == null){
            JSONObject jsonObject=JSON.parseObject(AESDecryption.decrypt(encryptedData,session_key,iv));
            phoneNumber=jsonObject.get("phoneNumber").toString();
        }
        if (nickname == null || nickname.equals(""))
        {
            nickname="nickname";
        }
        if (avatarUrl == null || avatarUrl.equals(""))
        {
            avatarUrl="avatarUrl";
        }
        if (gender == null || gender.equals("")){
            gender="null";
        }
//        if (openid == null){
//            JSONObject jsonObject= WechatUtil.getSessionKeyOrOpenId(code);
//            System.out.println("open:");
//            System.out.println(jsonObject.get("openid"));
//            openid =jsonObject.get("openid").toString();
//
//        }

//        微信表注册Entity
        WxUser wxUser=new WxUser();
//        主表注册Entity
        SysUser sysUser=new SysUser();
//        熊金表注册Entity
        Transfer transfer=new Transfer();
        wxUser.setWxOpenid(openid);
        if (wechatService.selectWxUserByOpenId(openid)==null){
            //            主表微信表注册Entity
            wxUser.setWxNickname(nickname);
            sysUser.setNickName(nickname);
            sysUser.setUserName(phoneNumber);
            sysUser.setPassword(phoneNumber);
//           Todo

            //            主表微信表注册Entity
            wxUser.setWxAvatarurl(avatarUrl);
            sysUser.setAvatar(avatarUrl);
//            主表微信表注册Entity
            wxUser.setWxGender(Integer.valueOf(gender));
//            sysUser.setSex(gender);
            //            主表微信表注册Entity
            wxUser.setWxPhoneNum(phoneNumber);
            sysUser.setPhonenumber(phoneNumber);
            {
                LocalDateTime now = LocalDateTime.now();
                System.out.println("当前时间：" + now);
                // 格式化输出
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDate = now.format(formatter);
                System.out.println("格式化时间：" + formattedDate);
                //            主表微信表注册Entity
                wxUser.setWxCTime(formattedDate);
                Date loginDate = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                     loginDate = dateFormat.parse(formattedDate);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                sysUser.setCreateTime(loginDate);
                sysUser.setLoginDate(loginDate);
                sysUser.setUpdateTime(loginDate);
                wxUser.setWxUTime(formattedDate);
            }
            iSysUserService.insertUser(sysUser);
            wechatService.insertWxUser(wxUser);
            SysUser sysUser1;
            try {
                sysUser1=iSysUserService.selectUserByUserName(phoneNumber);
            }
            catch (Exception e){
                return R.fail(405,"注册失败");
            }
            Integer transfer_id= Math.toIntExact(sysUser1.getUserId());
            transfer.setUserId(transfer_id);
            transfer.setUserPhone(phoneNumber);
            transfer.setUserName(nickname);
            transferService.insertTransfer(transfer);



        }
        else if (wechatService.selectWxUserByOpenId(openid)!=null){
            return R.fail(405,"该用户已注册");
        }
        return R.ok("注册成功");
    }
    @Anonymous
    @PostMapping("/wechat/confirm")
    public AjaxResult insTransfer(@RequestParam(value = "realname" ,required = true) String realname,
                                          @RequestParam(value = "identity",required = true) String identity,
                                          @RequestParam(value = "phone",required = true) String phone,
                                  @RequestParam(value = "userId",required = true) String userId) {
        System.out.println(userId);
        System.out.println(realname);
        System.out.println(identity);
        System.out.println(phone);
        Transfer transfer=new Transfer();
        transfer.setUserId(Integer.valueOf(userId));
        transfer.setUserName(realname);
        transfer.setUserIdCard(identity);
        transfer.setUserPhone(phone);
        System.out.println(transfer);
        try{
            if (personnelService.selectPersonnelByIDcard(transfer.getUserIdCard())!=null && personnelService.selectPersonnelByIDcard(transfer.getUserIdCard()).getpName().equals(transfer.getUserName())) {
//                如果存在于表中则插入
                if (transferService.selectTransferByPhone(transfer.getUserPhone())!=null){
                    return toAjax(transferService.updateTransfer(transfer));
                }
                return toAjax(0);
            }
            System.out.println("进入1");
            return AjaxResult.warn("身份证不存在或已认证，请确认信息后重新输入!!");
        }catch (DuplicateKeyException e)
        {
            System.out.println("进入2");
            return AjaxResult.warn("身份证不存在或已认证，请确认信息后重新输入!!");
        }
    }
}




